package vn.ikame.android.boojtran.truyenbua.download;

import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import vn.ikame.android.boojtran.truyenbua.SuperActivity;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import vn.ikame.android.boojtran.truyenbua.utility.CConstant;
import vn.ikame.android.boojtran.truyenbua.utility.XMLfunctions;
import android.os.AsyncTask;

public class ItemListDownload {
	private ItemListDowloadListener listener;
	private SuperActivity context;

	public ItemListDownload(SuperActivity context,
			ItemListDowloadListener listener) {
		this.context = context;
		this.listener = listener;
	}

	public void start(final String svr_link, final int start, final int count) {
		try {
			new AsyncTask<Void, Void, ArrayList<Item>>() {
				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					context.showProgress("Đang tải dữ liệu...");
				}

				@Override
				protected ArrayList<Item> doInBackground(Void... params) {
					return getListItem(svr_link, start, count);
				}

				@Override
				protected void onPostExecute(ArrayList<Item> result) {
					listener.onDownloadFinish(result, svr_link, start, count);
					context.dismissProgress();
					super.onPostExecute(result);
				}
			}.execute();
		} catch (Exception e) {
			listener.onDownloadError(svr_link, start, count);
			e.printStackTrace();
		}
	}

	private ArrayList<Item> getListItem(String svr_link, int start, int count) {
		String url = svr_link + "&start=" + start + "&count=" + count;
		ArrayList<Item> response = new ArrayList<Item>();
		try {
			String xml = XMLfunctions.getXML(url);
			Document doc = XMLfunctions.XMLfromString(xml);
			int numResults = XMLfunctions.numResults(doc);
			if ((numResults > 0)) {
				if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
					SuperActivity.totalItem = numResults;
				}
			}
			NodeList nodes = doc.getElementsByTagName("data");
			for (int i = 0; i < nodes.getLength(); i++) {
				Item item = new Item();
				Element e = (Element) nodes.item(i);
				try {
					item.setId(Integer.parseInt(XMLfunctions.getValue(e,
							CConstant.TAG_ID)));
				} catch (Exception ex) {
					item.setId(-1);
					ex.printStackTrace();
				}
				item.setTitle(XMLfunctions.getValue(e, CConstant.TAG_TITLE));
				item.setContent(XMLfunctions.getValue(e, CConstant.TAG_CONTENT));
				item.setImg(XMLfunctions.getValue(e, CConstant.TAG_IMG));
				if (item.getTitle() != null && item.getContent() != null
						&& !item.getContent().equals("")) {
					response.add(item);
				}
			}
		} catch (Exception e) {
			response = null;
			e.printStackTrace();
		}
		return response;
	}
}
